/**
 * Created by Administrator on 2016/8/16.
 * 处理照片
 */
var express = require('express');
var formidable = require('formidable');
var router = express.Router();
var Photo=require('../db/photo');
var path=require('path');
var fs=require('fs');
var qn=require('../utils/qn');


function photos(req, res,callback) {
    var page = req.query.page;
    if (!page) {
        page = 1;
    }
    var pageSize = 10;
    Photo.find().count(function (err, count) {
        var  totalPages =Math.ceil(count / pageSize);
        if(totalPages<page&&totalPages>0){
            page=page-1;
        }
        var query = Photo.find({});
        query.skip((page - 1) * pageSize);
        query.limit(pageSize);
        //计算分页数据
        query.exec(function (err, docs) {
            var policy = qn.policy();
            for (var i=0;i<docs.length;i++){
                docs[i].path = policy.makeRequest(docs[i].path);
            }
            if (err) {
                res.send(err);
            } else {
                callback(docs, count,page,totalPages);
            }
        });
    });

}
router.get('/', function (req, res) {
    photos(req, res,function(docs, count,page,totalPages){
        res.render('photos', {
            photos: docs,
            total: count,
            page: page,
            totalPages: totalPages
        });
    });
});


router.get('/delete', function(req, res, next) {
    var id=req.query.id;
    Photo.remove({_id:id}, function (err, doc) {
        if (err) {
            return;
        }

        var path=req.query.path.split("?")[0].split(".com/")[1];
        //删除资源
        qn.remove(req,path, function(err, ret) {
            if (!err) {
                photos(req, res,function(docs, count,page,totalPages){
                    res.render('photos1', {
                        photos: docs,
                        total: count,
                        page: page,
                        totalPages: totalPages
                    });
                });
            } else {
                console.log(err);
            }
        });

        // fs.unlink(path, function(err) {
        //     if (err) {
        //         return;
        //     }
        //     else{
        //         photos(req, res,function(docs, count,page,totalPages){
        //             res.render('photos1', {
        //                 photos: docs,
        //                 total: count,
        //                 page: page,
        //                 totalPages: totalPages
        //             });
        //         });
        //     }
        // });
    });
});
module.exports = router;